const jwt = require('jsonwebtoken')
const config   = require('./config')
const moment = require("moment/moment");
// 生成token
const createToken = async (userInfo, timeout = '5h') => {
    /*
      id:用户id,
      timeout:token过期时间
    */
    const token_info = {
        userInfo,
        ctime: new Date().getTime(), //token创建时间戳
    }
    const token = await jwt.sign(token_info, config.secret, { expiresIn: timeout }) // 生成token
    return token
}

// 校验token
const varifyToken = async old_token => {
    try {
        const userInfo = await jwt.verify(old_token.split(' ')[1],config.secret)
        return userInfo
    } catch (err) {
        // token已过期
        // return (console.log('varifyToken >>> ' + err))
        return false
    }
}

const removeEmptyValues = (obj) =>{
    for (const key in obj) {
        if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
            delete obj[key];
        } else if (typeof obj[key] === 'object' && Object.keys(obj[key]).length === 0) {
            delete obj[key];
        }
    }
    return obj;
}
/**
 * @author:  maybe
 * @date: 2024/1/8 
 * @des: 生成唯一的id
 */
const generateUUID  = ()=> {
    return  moment().format('yyyyMMDD') + Math.floor(Math.random() * Math.pow(10, 10))
}



module.exports = {
    removeEmptyValues,
    varifyToken,
    createToken,
    generateUUID

}
